< previous page page_165 next page >

Page 165
Visual Basic automatically sets aside space for implicitly declared variables the first time each variable is encountered. The variables that were declared using the code in the preceding section could have been used as implicitly declared variables, as follows:
nNumVal% = 0
nAvgVal% = 1
vInptVal = 5
fClcAverage! = 10.1
sFirstName$ = "Lauren"
Notice that the variable vInptVal doesn't have a declaration character. This means that vInptVal will be of the Variant type.
Fixed-Length Strings
Most strings that you use in your programs will be of the type known as variable-length strings. These strings can contain any amount of text, up to approximately 2 billion characters. As information is stored in the variable, the size of the variable adjusts to accommodate the length of the string. Both the implicit and explicit declarations shown earlier created variable-length strings. Visual Basic, however, does have a second type of string: the fixed-length string.
As the name implies, a fixed-length string remains the same size, regardless of the information assigned to it. If a fixed-length string variable is assigned an expression shorter than the defined length of the variable, the remaining length of the variable is filled with spaces. If the expression is longer than the variable, only as many characters as will fit in the variable are stored; the rest are truncated.
A fixed-length string variable can only be declared using an explicit declaration like the following:
Dim varname As String * strlength
Notice that this declaration is slightly different from the previous declaration of a string variable. The declaration of a fixed-length string variable contains an asterisk (*) to tell Visual Basic that the string will be of a fixed length. The final parameter, strlength, tells the program the maximum number of characters that the variable can contain.
One example of a fixed-length string is to aid in building a column-delimited text file. Suppose 25 characters of the file are used to represent a person's name. The following code would automatically cut the string off at 25 characters:
Dim sName As String * 25
sName = "This text is too long for the string variable."
Assigning a value less than 25 characters in length to sName would make the remaining characters spaces.
note.gif Another common use of fixed-length strings is to receive information from a Windows API function, as discussed in Chapter 20, "Accessing the Windows API." square.gif

 
< previous page page_165 next page >